package com.wxmp.core.util;


import java.io.StringWriter;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import org.apache.commons.lang.RandomStringUtils;
import lombok.extern.java.Log;

@Log
public class PayUtils {

    
    
    public static void main(String[] args) {
        String signMsg = "inputCharset=1&receiveUrl=www.baidu.com&version=v1.0&" + 
                "language=1&signType=1&merchantId=100020091219001&payerName=全渠道&" + 
                "payerTelephone=13552535506&payerAcctNo=6216261000000000018&" + 
                "payerIdType=01&payerIdNo=341126197709218000&orderNo=2009213322&" + 
                "orderAmount=1000&orderCurrency=156&orderDatetime=20090115133622&" + 
                "productName=商品名称&payType=98&issuerId=unionpay&" + 
                "key=1234567890";
        System.out.println(MD5Encode(signMsg));
        
    }
    //map排序
    public static String getSign(Map<String, Object> map) {
        String result = "";
        try {
            List<Map.Entry<String, Object>> infoIds = new ArrayList<Map.Entry<String, Object>>(map.entrySet());
            // 对所有传入参数按照字段名的 ASCII 码从小到大排序（字典序）
            Collections.sort(infoIds, new Comparator<Map.Entry<String, Object>>() {
                public int compare(Map.Entry<String, Object> o1, Map.Entry<String, Object> o2) {
                    return (o1.getKey()).toString().compareTo(o2.getKey());
                }
            });
            // 构造签名键值对的格式
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, Object> item : infoIds) {
                if (item.getKey() != null || item.getKey() != "") {
                    String key = item.getKey();
                    String val = item.getValue().toString();
                    if (!(val == "" || val == null)) {
                        sb.append(key + "=" + val + "&");
                    }
                }
            }
//          sb.append(PropertyManager.getProperty("SIGNKEY"));
            result = sb.toString();
            
            //进行MD5加密
//            result = DigestUtils.md5Hex(result).toUpperCase();
        } catch (Exception e) {
            return null;
        }
        return result;
    }

    
    //随机生成字符串
    public static String random() {
        String random = RandomStringUtils.random(18, true, true);
        log.info(random);
        return random;
    }
    
    
    
    
    //将map转换成xml文件
    public static String map2xml(Map<String, Object> map, String rootElement)
    {
        StringBuffer xmlStr = new StringBuffer("");
        xmlStr.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><" + rootElement + ">");
        map2Element(map, xmlStr);
        xmlStr.append("</" + rootElement + ">");
        return xmlStr.toString();
    }


    @SuppressWarnings("unchecked")
    private static void map2Element(Map<String, Object> map, StringBuffer sb)
    {
        Set<String> set = map.keySet();
        for (Iterator<String> it = set.iterator(); it.hasNext();)
        {
            String key = (String)it.next();
            Object value = map.get(key);
            if (null == value)
                value = "";
            if (value instanceof List<?>)
            {
                List<Object> list = (List<Object>)map.get(key);
                sb.append("<" + key + ">");
                for (int i = 0; i < list.size(); i++)
                {
                    Map<String, Object> hm = (Map<String, Object>)list.get(i);
                    map2Element(hm, sb);
                }
                sb.append("</" + key + ">");
            }
            else
            {
                if (value instanceof Map<?, ?>)
                {
                    sb.append("<" + key + ">");
                    map2Element((Map<String, Object>)value, sb);
                    sb.append("</" + key + ">");
                }
                else
                {
                    sb.append("<" + key + ">" + value + "</" + key + ">");
                }
                
            }
        }
    }

    
    
    
    //实体类转换成xml
    public static String convertToXml(Object obj) {
        StringWriter sw = new StringWriter();
        try {
            JAXBContext context = JAXBContext.newInstance(obj.getClass());
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
                    Boolean.TRUE);
            marshaller.marshal(obj, sw);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return sw.toString().replace("standalone=\"yes\"", "");
    }

    
    
    //MD5加密
    public static String MD5Encode(String aData) throws SecurityException {
        String resultString = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            resultString = bytes2HexString(md.digest(aData.getBytes("UTF-8")));
        } catch (Exception e) {
            e.printStackTrace();
            throw new SecurityException("MD5运算失败");
        }
        return resultString;
    }

    public static String bytes2HexString(byte[] b) {
        String ret = "";
        for (int i = 0; i < b.length; i++) {
            String hex = Integer.toHexString(b[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            ret += hex.toUpperCase();
        }
        return ret;
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
}
























